package com.freewater.javabase.demo.nio;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class FilesDemo {
    public static void main(String[] args) {
        // exists
        final Path path = Paths.get("src/main/java/com/freewater/javabase/demo/nio/FilesDemo.java");
        System.out.println(path.toAbsolutePath());
        final boolean exists = Files.exists(path);
        System.out.println(exists);

        // create dir
        final Path dirPath = Paths.get("data/subdir");
        if (!Files.exists(dirPath)) {
            try {
                Files.createDirectory(dirPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(dirPath.toAbsolutePath() + " already exists");
        }
        // copy
        final Path sourcePath = Paths.get("data/nio-data.txt");
        final Path destinationPath = Paths.get("data/nio-data-copy.txt");
        if (!Files.exists(destinationPath)) {
            try {
                Files.copy(sourcePath, destinationPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(destinationPath.toAbsolutePath() + " already exists");
        }

        // walkFileTree
        try {
            Files.walkFileTree(Paths.get("src/main/java"), new FileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    System.out.println("pre visit dir:" + dir);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    System.out.println("visit file: " + file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    System.out.println("visit file failed: " + file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    System.out.println("post visit directory: " + dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
